﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using KnowledgeKiosk.Objects;
using System.Windows.Browser;

namespace KnowledgeKiosk.Parsers
{
    /// <summary>
    /// Provides a way to deserialize XML data to BlogPost objects. 
    /// </summary>
    public class BlogPostsParser : IXmlToObjectParser<IEnumerable<BlogPost>>
    {
        private static readonly XNamespace dc = "http://purl.org/dc/elements/1.1/";

        #region IXmlToObjectParser<IEnumerable<BlogPost>> Members

        /// <summary>
        /// Deserializes XML to a collection of BlogPost objects.
        /// </summary>
        /// <param name="xml">The XML data to deserialize.</param>
        /// <returns>The deserialized collection of BlogPost objects.</returns>
        public IEnumerable<BlogPost> Parse(XElement xml)
        {
            return xml.Element("channel").Elements("item").Select(x => ToPost(x)).ToList();
        }

        #endregion

        /// <summary>
        /// Deserializes XML data to a single BlogPost object.
        /// </summary>
        /// <param name="node">The XML data to deserialize.</param>
        /// <returns>The deserialized BlogPost object.</returns>
        private BlogPost ToPost(XElement node)
        {
            var post = new BlogPost();
            post.Title = node.Element("title").Value ?? "<Titel>";

            string description = node.Element("description").Value ?? "<Omschrijving>";

            int eod = description.LastIndexOf("&#8230;");
            if (eod >= 0)
            {
                description = description.Substring(0, eod);
                description += "...";
            }

            post.Description = HttpUtility.HtmlDecode(description);

            post.Author = node.Element(dc + "creator").Value ?? "<Auteur>";

            return post;
        }
    }
}